package com.guyu.common.core.entity;

import lombok.Getter;
import lombok.NoArgsConstructor;

/**
 * <p> 分页请求对象 </p>
 */
@Getter
@NoArgsConstructor
public class PageRequest implements java.io.Serializable {

    private static final long serialVersionUID = -3249240106177676069L;
    /**
     * 页码，从1开始
     */
    private long page = 1L;
    /**
     * 每页显示数量[1,1000]
     */
    private int size = 10;


    private PageRequest(long page, int size) {
        if (page < 1) {
            throw new IllegalArgumentException("Page index must not be less than 1!");
        }
        if (size < 1) {
            throw new IllegalArgumentException("Page size must not be less than 1!");
        }
        if (size > 1000) {
            throw new IllegalArgumentException("Page size must not be greater than 1000!");
        }

        this.page = page;
        this.size = size;
    }

    public static PageRequest of(long page, int size) {
        return new PageRequest(page, size);
    }


    public void setSize(int size) {
        if (size < 1) {
            throw new IllegalArgumentException("Page size must not be less than 1!");
        }
        if (size > 1000) {
            throw new IllegalArgumentException("Page size must not be greater than 1000!");
        }
        this.size = size;
    }

    public void setPage(long page) {
        if (page < 1) {
            throw new IllegalArgumentException("Page index must not be less than 1!");
        }
        this.page = page;
    }

    /**
     * 起始位置，偏移位置
     */
    public long getOffset() {
        return (page - 1) * size;
    }

    /**
     * 是否有上一页
     */
    public boolean hasPrevious() {
        return page > 1;
    }

    /**
     * 下一页
     */
    public PageRequest next() {
        return new PageRequest(getPage() + 1, getSize());
    }

    /**
     * 上一页
     */
    public PageRequest previous() {
        return getPage() == 1 ? this : new PageRequest(getPage() - 1, getSize());
    }

    /**
     * 第一页
     */
    public PageRequest first() {
        return new PageRequest(1, getSize());
    }

    /**
     * 如果当前页已经是第一页，则返回第一页否则返回前一页
     */
    public PageRequest previousOrFirst() {
        return hasPrevious() ? previous() : first();
    }
}
